// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Popconfirm, Row, Col, Button, Input, Table, DatePicker ,Select ,Cascader,Tabs ,Modal ,Icon,message} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config, { listConfig } from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './codeChannelStatisticsStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames';
import ReactEcharts from 'echarts-for-react';
import moment from 'moment'
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
import Chart from 'widget/Chart/chart'
import Img from '../../../assets/img/shangxin.png'
import { makeAddress } from "utils/util"

const FormItem = Form.Item
const Option = Select.Option
const { MonthPicker, RangePicker } = DatePicker
const TabPane = Tabs.TabPane;
let useColumns

/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const codeChannelStatisticsView = function ({ dispatch, model, form }) {
	// 表单的子函数
	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
	// 取出model对象，命名空间
	const { modelObj, namespace } = model

	let { area1,products,reports,params1,params,loading,dataList,name,dateList,visible,query1,contrast,roleType,time,time1,statisticsContent,productId,regionId,selectValue,title,productName,selected,selected2,graphRespDtos,otherSkip,areaList} = modelObj 
	function goRoute(item,roleType,areaId){
		let type=roleType,id=item.tableRowType || null
		let contrastType=item.contrastType || null ,regionId=null
		if(roleType==2){
			regionId=params1.contrastData
		}
		if(roleType==3){
			regionId=areaId
			item.productId=productId
		}
		if(item.tableRowType==-2){
			type=2
			id=null
		}
		if(roleType=='search'){
			if(item.tableRowType!=''){
				type=1
				contrastType='3'
				id=item.tableRowType
				regionId=item.tableRowType
			}
			if(item.productId){
				type=2
				id=item.productId
				contrastType='1'
			}
		}
		let url=['','/home/codeChannelAdmin/codeChannelArea','/home/codeChannelAdmin/codeChannelProject','/home/codeChannelAdmin/codeChannelCanals']
		hashHistory.push({
			pathname:url[type],
			query: {id:id,contrastType:contrastType,productId:type==3?params1.contrastData || item.productId:null,regionId,title,selected2,startTime:time1.startTime,endTime:time1.endTime,otherSkip:item.otherSkip || null,cityCode:params.cityCode[1] || null,provinceCode:params.cityCode[0] || null}
		});
	}
	const  formItemLayout = {
			labelCol: { span: 8 },
			wrapperCol: { span: 16 },
	};
	let selected1=''
	// 点击处理事件
	const clickHandler = (e) => {
		// 分发到model文件中effects的xxx方法
		dispatch({
			type: `${namespace}/xxx`,
			payload: {}
		});
	}
	let maxNum=[]
    dataList.map((item,index)=>{
		return maxNum=maxNum.concat(item.data)
	})
	function useColumns1(){
		 useColumns = [	
			{
			dataIndex: "tableRowTypeName",
			title: ["","区域名称","项目名称","类别名称","渠道名称"][roleType],
			},
			{
			dataIndex: "summaryValueDto.scanCnt",
			title: "扫码次数",
			},
			{
			dataIndex: "summaryValueDto.ratio",
			title: "占比",
			render:(text,record,index)=>{
				return <span>{text}%</span>
			}
			},
			{
			dataIndex: "summaryValueDto.registerCnt",
			width:150,
			title: "新注册用户数",
			},
			{
			dataIndex: "summaryValueDto.referralsCnt",
			title: "推介客户数"
			},
			{
			dataIndex: "summaryValueDto.appointmentCnt",
			title: "预约看房数",
			},
			{
			dataIndex: "summaryValueDto.attentionCnt",
			title: "关注楼盘数",
			},
			{
				dataIndex: "summaryValueDto.recognitionCnt",
				title: "认筹客户数",
			},
			{
			dataIndex: "summaryValueDto.subscriptionCnt",
			title: "认购客户数",
			},
			{
				title: "操作",
				dataIndex: "contrastType",
				render:(text,record,index)=>{

					if(record.tableRowType!=-1 && record.tableRowType!='null' && !(record.tableRowType==-2 && !record.otherSkip)){
						return <a  onClick={()=>{
							 goRoute(record,roleType,regionId)
							
						}}>{['','项目明细','传播渠道明细','渠道明细'][roleType]}</a>
					}
					
				}
		},
	];
	if(roleType==4){
		let m = useColumns.slice(0);
		m.splice(m.length-1,1);
		useColumns=m
	}
}
useColumns1()
	function callback(key){
		dispatch({
			type:`${namespace}/updateStore`,
			payload:{
				query1:{
					...query1,
					dataType:key
				}
			}
		})
		dispatch({
			type:`${namespace}/getReport`,
			payload:{
				dataType:key
			}
		})
		dispatch({
			type:`${namespace}/getChart`,
			payload:{
				dataType:key
			}
		})
		
	}

	function onChange(dates, dateStrings) {
		dispatch({
			type:`${namespace}/updateStore`,
			payload:{
				time:{
					startTime:dateStrings[0],
					endTime:dateStrings[1]
				}
				
			}
		})
		dispatch({
			type:`${namespace}/getChart`,
			payload:{
				
			}
		})
	}
	function onChange2(dates, dateStrings) {
		dispatch({
			type:`${namespace}/updateStore`,
			payload:{
				time1:{
					startTime:dateStrings[0],
					endTime:dateStrings[1]
				}
				
			}
		})
		dispatch({
			type:`${namespace}/getReport`,
			payload:{
				
			}
		})
	}

		let option = {
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data:name,
				},
				color: ['#409EFF', '#67C23A','#F57C08','#F2F20A','#F703D3','#264463','#FA2C03','#FACBCB','#FA00E5','#8E2121','#0DF7E8','#A2A2F7','#1717F7','#89831C','#46ED21','#AAF798','#B9FACB','#F7E8AA','#FAD343','#ccc'],
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true,
					y:'30%',
				},
				xAxis: {
					type: 'category',
					name: '时间',
					boundaryGap: false,
					data: dateList
				},
				yAxis: {
					type: 'value',
					name: '次数',
					splitNumber:Math.max.apply(null,maxNum)<=1?1:null,
				},
				series:dataList
			};
	
	function confirmHref(){
	}
	function inputChange(e,name){
		if(name=='tableRowType'){
			area1.map((item,index)=>{
				if(item.value==e){
					if(item.children.length){
						areaList = makeAddress(item.children,2)
					}
				}
			})
		}else if(name==='time'){
			dispatch({
				type:`${namespace}/updateStore`,
				payload:{
					time:{
						startTime:e=='7'?moment().subtract(6, 'days').format('YYYY-MM-DD'):(e=='30'?moment().subtract(29, 'days').format('YYYY-MM-DD'):time.startTime),
						endTime:moment().format('YYYY-MM-DD')
					},
					selected:e,
				}
			})
			dispatch({
				type:`${namespace}/getChart`,
				payload:{
					
				}
			})
		}else if(name==='time1'){
			dispatch({
				type:`${namespace}/updateStore`,
				payload:{
					time1:{
						startTime:e=='7'?moment().subtract(6, 'days').format('YYYY-MM-DD'):(e=='30'?moment().subtract(29, 'days').format('YYYY-MM-DD'):time1.startTime),
						endTime:moment().format('YYYY-MM-DD')
					},
					selected2:e,
				}
			})
			dispatch({
				type:`${namespace}/getReport`,
				payload:{
				}
			})
		}
		dispatch({
			type:`${namespace}/updateStore`,
			payload:{
				params:{
					...params,
					[name]:e
				},
				products,
				areaList
			}
		})
	}
	function search(type){
		if(localStorage.getItem('roleType')==3 && params.tableRowType){
			if(!params.productId && type!='reset'){
				message.error('请选择项目')
				return false
			}
		}
		dispatch({
			type:`${namespace}/updateStore`,
			payload:{
				loading:true,
				params:type=='reset'?{}:params
			}
		})
		//    goRoute(params,'search',regionId)
		if(type!='reset'){
			if(params.tableRowType){
				if(!params.productId && localStorage.getItem('roleType')==2){
					if(roleType==2){
						query1.statisticsContent[0]=params.tableRowType
						query1.contrastType='3'
						dispatch({
							type:`${namespace}/updateStore`,
							payload:{
								query1
							}
						})
						dispatch({
							type:`${namespace}/getChart`,
							payload:{
								
							}
						})
						dispatch({
							type:`${namespace}/getReport`,
							payload:{
							}
						})
					}else if(roleType==3){
						hashHistory.push({
							pathname:'/home/codeChannelAdmin/codeChannelClique',
							query: {statisticsContent:params.tableRowType,contrastType:'3'}
						});
					}
				}else if(params.productId && localStorage.getItem('roleType')==3 && roleType==3){
					query1.regionId=params.tableRowType
					query1.productId=params.productId
					query1.contrastType='1'
					dispatch({
						type:`${namespace}/updateStore`,
						payload:{
							query1
						}
					})
					dispatch({
						type:`${namespace}/getChart`,
						payload:{

						}
					})
					dispatch({
						type:`${namespace}/getReport`,
						payload:{
							
						}
					})
				}else{
					goRoute(params,'search',regionId)
				}
			}
			
		}
	}
	return (
		<div className={cx('pageLayout')} className={styles.detail}>	
            <Form>
                <Row>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label='所属区域'>
                        {getFieldDecorator('tableRowType',{
                                initialValue:!otherSkip && params.tableRowType || ''
                            })(
                            <Select placeholder='请选择区域'  onChange={e=>{
								setFieldsValue({productId:'',cityCode:[]})
								params.productId=null
								dispatch({
									type:`${namespace}/updateStore`,
									payload:{
										params
									}
									
								})
								inputChange(e,'tableRowType')
							}}>
                                {area1.map((item)=>{
                                   return <Option key={item.value} value={item.value}>{item.label}</Option>
                                })}
                            </Select>)}
                        </FormItem>
                    </Col>
					<Col span={6}>
                        <FormItem {...formItemLayout}  label='所属城市'>
                        {getFieldDecorator('cityCode', {
                                initialValue: params.cityCode
                            })(
								<Cascader placeholder='请选择城市'  options={areaList}  onChange={e=>{
									setFieldsValue({productId:''})
										inputChange(e,'cityCode')} }>
								</Cascader>
							)}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem {...formItemLayout}  label='所属项目'>
                        {getFieldDecorator('productId', {
                                initialValue:params.cityCode && params.cityCode.length && params.cityCode.length>0?params.productId:null
                            })(
                                <Select placeholder='请选择项目'  onChange={e=>{
									inputChange(e,'productId') 
								}} onFocus={()=>{
											dispatch({
												type:`${namespace}/getProduct`,
												payload:{}
											})
									}								
								}>
                                {products.map((item)=>{
                                   return <Option key={item.value} value={item.value}>{item.label}</Option>
                                })}
                            </Select>)}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <Col span={4} offset={10}>
                                <Button type="primary" htmlType="submit" disabled={area1.length==1 && area1[0].products.length==1} onClick={() => { search()}}>搜索</Button>
                        </Col>
                        <Col span={4} offset={2}>
                                    <Button disabled={area1.length==1 && area1[0].products.length==1}  onClick={() => {
									resetFields()
									dispatch({
										type:`${namespace}/updateStore`,
										payload:{
											products:[]
										}
									})
									search('reset')
									}} >重置</Button>
                        </Col>
                    </Col>
                </Row>
            </Form>
			{
				localStorage.getItem('roleType')==3 && graphRespDtos.length== 0 && roleType==3?<div style={{marginTop:'100px',marginLeft:'250px',display:'flex',alignItems:'center'}}>
					<img style={{width:'90px',height:'90px'}} src={Img}></img>
					<span style={{width:'400px',display:'inline-block',marginLeft:'10px',fontSize:'14px',fontWeight:600}}>温馨提示：<div>你所在的项目，未使用过项目二维码，故缺少相应的数据统计信息，快去【楼盘管理】下载二维码体验吧，<a href='javascript:void(0)' onClick={()=>{
						hashHistory.push({
							pathname:'/home/buildingAdmin/baseinfo',
							query:{}
						})
						
					}}>点我跳转...</a></div></span>
				</div>
				:<div>
					<CollapsiblePanels dataIndex="渠道分析" >
						<div className="public_listMain">
							<div className="boxShadow listSearchBox">
								<Row>
								<span style={{fontSize:'16px',marginBottom:'20px',display:'block'}}>{roleType==4 && productName}{roleType==4 && productName && '-'}传播渠道统计 - {title}</span>
								</Row>
								<Row>
									<span>Top5</span><Button type='primary' onClick={()=>{
										dispatch({
											type:`${namespace}/updateStore`,
											payload:{
												visible:true
											}
										})
										dispatch({
											type:`${namespace}/getContrast`,
											payload:{
												
											}
										})
									}}>+{['','区域选择','项目选择','类别对比','渠道对比'][roleType]}</Button>
								</Row>
								<Row>
									<Col span={14}>
											<Tabs onChange={callback}>
												<TabPane tab='扫码次数' key='1'></TabPane>
												<TabPane tab='新注册用户数' key='2'></TabPane>
												<TabPane tab='推介客户数' key='3'></TabPane>
												<TabPane tab='预约看房数' key='4'></TabPane>
												<TabPane tab='楼盘关注数' key='5'></TabPane>
												<TabPane tab='认购客户数' key='6'></TabPane>
											</Tabs>
									</Col>
									
									<Col span={9}>
										<div style={{height:'32px',display:'flex'}}>
											<span style={{width:'100px',display:'block',marginRight:'20px'}}>
												<Select onChange={e=>{
													inputChange(e,'time')
												}}  value={selected} defaultValue='7'>
													<Option value='1'>自定义</Option>
													<Option value='7'>最近7天</Option>
													<Option value='30'>最近30天</Option>
												</Select>
											</span>
											{selected!=1?<span  style={{lineHeight:'32px'}}>{time.startTime}至{time.endTime}</span>:
											<RangePicker 
												format='YYYY-MM-DD'
												onChange={onChange}
												value={[moment(time.startTime, 'YYYY/MM/DD'), moment(time.endTime, 'YYYY/MM/DD')]}
											/>}
										</div>
										
									</Col>
									
								</Row>
							</div>
						</div>
						<div>
							<Chart Option={option}></Chart>
						{/* <ReactEcharts
							option={option}
							ref={(el)=>{chart = el}}
						></ReactEcharts> */}
						</div>
					</CollapsiblePanels>
					<CollapsiblePanels title={<div><span>传播渠道汇总</span><a style={{'color':'#666','marginLeft':'20px'}} onClick={()=>{
						dispatch({
							type:`${namespace}/down`,
							payload:{}
						})
					}}><Icon type="vertical-align-bottom" />下载EXCEL</a></div>} sTitle={<div className={styles.date}>
						
						<Col span={6}>
							<Select onChange={e=>{
								inputChange(e,'time1')
							}}  value={selected2} defaultValue='7'>
								<Option value='1'>自定义</Option>
								<Option value='7'>最近7天</Option>
								<Option value='30'>最近30天</Option>
							</Select>
						</Col>
						{selected2!=1?<span style={{    fontFamily: "Microsoft Yahei",fontSize: '12px',
			fontWeight: 'normal',color: '#333',marginLeft:'30px'}}>{time1.startTime}至{time1.endTime}</span>:
										<RangePicker  
											format='YYYY-MM-DD'
											onChange={onChange2} 
											value={[moment(time1.startTime, 'YYYY/MM/DD'), moment(time1.endTime, 'YYYY/MM/DD')]}

										/>
									}
						</div>}  className={styles.basicInfo}>
						<Table
							dataSource={reports}
							columns={useColumns}
							pagination={false}
						/>
					</CollapsiblePanels>
					<Modal
					visible={visible}
					onOk={()=>{
						query1.contrastData=selectValue
						dispatch({
							type:`${namespace}/updateStore`,
							payload:{
								visible:false,
								query1
							}
						})
						dispatch({
							type:`${namespace}/getChart`,
							payload:{
							}
						})
					}}
					onCancel={() => {
						dispatch({
							type:`${namespace}/updateStore`,
							payload:{
								visible:false
							}
						})
					}}
					width={'45%'}>
						<CollapsiblePanels title={`增加${['','区域对比','项目对比','类别对比','渠道对比'][roleType]}`} >
							<Row>
								<Col span={6}>
									<span>
										增加{['','区域对比','项目对比','类别对比','渠道对比'][roleType]}：
									</span>
								</Col>
								<Col span={12}>
									<Select mode="tags"
									defaultValue={selectValue}
									value={selectValue}
									onChange={e=>{
											selected1=e
											dispatch({
												type:`${namespace}/updateStore`,
												payload:{
													selectValue:e
												}
											})
										}
									}>
										{
											contrast.length&&contrast.map((item,index)=>{
												return <Option value={item.contrastKey}>{item.contrastName}</Option>
											})
										}
										{/* {
											area1.map((item,index)=>{
												return <Option value={item.value}>{item.label}</Option>
											})
										} */}
									</Select>
								</Col>
							</Row>
						</CollapsiblePanels>
						
					</Modal>
				</div>
			}
		</div>
	)
}
// 连接视图(view)和模型(model)
export default Form.create()(codeChannelStatisticsView)
